package com.meisiabc.app.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.meisiabc.app.service.ProfileService;
import com.meisiabc.app.service.SmsCodeService;
import com.meisiabc.app.service.WechatService;
import com.meisiabc.support.Result;
import com.meisiabc.utils.Verify;
import com.riversoft.weixin.common.decrypt.AesException;
import com.riversoft.weixin.common.decrypt.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import static com.meisiabc.app.service.SmsCodeService.WECHAT_MP;

@Slf4j
@Controller
@RequestMapping("/wechat/mp")
public class WechatController {
    @Autowired
    private WechatService wechatService;
    @Autowired
    private SmsCodeService smsCodeService;
    @Autowired
    private ProfileService profileService;

    @GetMapping("/server")
    @ResponseBody
    public String wxServer_get(String signature, String timestamp, String nonce, String echostr) {
        String signature_cal = "";
        try {
            signature_cal = SHA1.getSHA1(timestamp, nonce, "meisiabcwechat");
        } catch (AesException e) {
            log.error("", e);
        }
        Verify.isTrue(signature.equals(signature_cal), "校验错误");
        return echostr;
    }

    @PostMapping("/server")
    @ResponseBody
    public String wxServer_post(@RequestBody String msg) {
        return wechatService.dealMsg(msg);
    }

    @GetMapping("/login/page")
    public String wechatLoginPage() {
        return "redirect:" + wechatService.wechatLoginPage();
    }

    @GetMapping("/login")
    public String wechatLogin(@RequestParam String code) {
        String openId = wechatService.wechatLogin(code);
        if (wechatService.alreadyBind(openId)) {
            return "redirect:https://meisiabc.cn/app/#/wechat/bind_success";
        }

        return "redirect:https://meisiabc.cn/app/#/wechat/bind/" + openId;
    }

    @GetMapping("/sms")
    @ResponseBody
    public Result sms(@RequestParam String mobile) {
        profileService.assertRegisted(mobile);
        smsCodeService.sendSms(WECHAT_MP, mobile);
        return Result.ok();
    }

    @PostMapping("/login")
    @ResponseBody
    public Result smsLogin(@RequestBody JSONObject loginForm) {
        String openid = loginForm.getString("openid");
        String mobile = loginForm.getString("mobile");
        String smsCode = loginForm.getString("sms_code");

        smsCodeService.verifySmsCode(WECHAT_MP, mobile, smsCode);
        Verify.isTrue(!wechatService.alreadyBind(openid), "该微信已经绑定手机号");
        wechatService.smsLogin(openid, mobile, DateTime.now());
        return Result.ok();
    }

    @GetMapping("/menu/init")
    @ResponseBody
    public Result menu_init() {
        wechatService.menuInit();
        return Result.ok();
    }

}
